//
//  ZYCProtalNoticePushPeopleViewController.m
//  ZDSC
//
//  Created by ZDTX on 2021/8/18.
//

#import "ZYCProtalNoticePushPeopleViewController.h"
#import "ZYCProtalNoticePushPeopleCell.h"
#import "ZYCProtalNoticePushDeptCell.h"
#import "ZYCRoleTreeModel.h"
#import "ZYCSearchBarView.h"
#import "UIButton+EnlargeEdge.h"
#import "ZYCFliterMultipleChoiceView.h"
@interface ZYCProtalNoticePushPeopleViewController ()<UITableViewDataSource,UITableViewDelegate,ZYCSearchBarViewDelegate,ZYCFliterMultipleChoiceViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIButton *comfirmButton;
@property (nonatomic, strong) ZYCSearchBarView *searchView;
@property (nonatomic, strong) ZYCFliterMultipleChoiceView *fliterView;
// 总人数
@property (nonatomic, strong) NSArray *totalArray;
//搜索人数
@property (nonatomic, strong) NSArray *searchResultArray;

@property (nonatomic, assign) BOOL isSelected;
// 关键字搜索
@property (nonatomic, copy) NSString *keyword;
@property (nonatomic, strong) NSMutableArray *selectArray;
@property (nonatomic, assign) BOOL searchActive;

@end

@implementation ZYCProtalNoticePushPeopleViewController

#pragma mark - Life Cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = self.titleString;
    [self.view addSubview:self.searchView];
    [self.view addSubview:self.tableView];
    self.totalArray = [self filterSource:self.dataSource type:@"4"];
    self.searchResultArray = self.totalArray ;
    self.fliterView.dataSource = self.searchResultArray;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.comfirmButton];
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.tableView reloadData];
    
    NSInteger count = 0;
    for (ZYCRoleTreeModel *model in self.dataSource) {
        if ([model.dateType integerValue] == 4) {
            if (model.isSelected) {
                count ++;
            }
        }else{
            count = count + model.selectedCnt;
        }
    }
    [self.comfirmButton setTitle:[NSString stringWithFormat:@"确认(%zd)",count] forState:UIControlStateNormal];
    [self.comfirmButton sizeToFit];

}


#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ZYCRoleTreeModel *model = self.dataSource[indexPath.row];
    if ([model.dateType integerValue] == 4) {// 家长  or 教师
        ZYCProtalNoticePushPeopleCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ZYCProtalNoticePushPeopleCell class]) forIndexPath:indexPath];
        cell.selectAction = ^(BOOL isSelected) {
            model.selectArr = [self childrenArr:model.children select:isSelected];
            [self fatherSelectArr:model.father];
            NSInteger count = 0;
            for (ZYCRoleTreeModel *model in self.dataSource) {
//                count = count + model.selectedCnt;
                if (model.isSelected) {
                    count ++;
                }
            }
            [self.comfirmButton setTitle:[NSString stringWithFormat:@"确认(%zd)",count] forState:UIControlStateNormal];
            [self.comfirmButton sizeToFit];
            [self.tableView reloadData];
        };
        cell.model = self.dataSource[indexPath.row];
        return cell;
    }else{
        ZYCProtalNoticePushDeptCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ZYCProtalNoticePushDeptCell class]) forIndexPath:indexPath];
        cell.selectAction = ^(BOOL isSelected) {
            model.selectArr = [self childrenArr:model.children select:isSelected];
            [self fatherSelectArr:model.father];
            

            NSInteger count = 0;
            for (ZYCRoleTreeModel *model in self.dataSource) {
                count = count + model.selectedCnt;
            }
            
            [self.comfirmButton setTitle:[NSString stringWithFormat:@"确认(%zd)",count] forState:UIControlStateNormal];
            [self.comfirmButton sizeToFit];
            
   
            [self.tableView reloadData];
            
        };
        cell.model = self.dataSource[indexPath.row];
        return cell;
    }
}



-(CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 5.0f;
}

-(CGFloat) tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 48.0f;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [UIView new];
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *v = [[UIView alloc] init];
    v.backgroundColor =  HEX_RGB(@"#F9F9F9");
    return v;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    ZYCRoleTreeModel *model = self.dataSource[indexPath.row];
    if (model.children.count > 0) {
        ZYCProtalNoticePushPeopleViewController *vc = [ZYCProtalNoticePushPeopleViewController new];
        vc.dataSource = model.children;
        vc.titleString = model.label;
        [self.navigationController pushViewController:vc animated:YES];
    }
}


#pragma mark - ZYCFliterMultipleChoiceViewDelegate
- (void)fliterMultipleChoiceView:(FliterMultipleChoiceView *)view selectArr:(NSArray *)selectArr{
    [self.selectArray removeAllObjects];
    for (ZYCRoleTreeModel *model in selectArr) {
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setObject:model.r_id forKey:@"userId"];
        [dict setObject:model.label forKey:@"userName"];
        [self.selectArray addObject:dict];
    }

    [self.comfirmButton setTitle:[NSString stringWithFormat:@"确认(%zd)",selectArr.count] forState:UIControlStateNormal];
    [self.comfirmButton sizeToFit];
    

    
}

#pragma mark - ZYCSearchBarViewDelegate
- (void)searchBarViewDidTextDidChange:(NSString *)searchText height:(CGFloat)height{
    self.fliterView.frame = CGRectMake(0, CGRectGetMaxY(self.searchView.frame), kScreenWidth, kScreenHeight - CGRectGetMaxY(self.searchView.frame) - height);
    NSLog(@"搜索关键字:%@",searchText);
    self.keyword = searchText;
    if (searchText.length > 0) {
        self.fliterView.hidden = NO;
        
    }else{
        self.fliterView.hidden = YES;
    }
}



#pragma mark - setters
- (void)setKeyword:(NSString *)keyword{
    _keyword = keyword;
    if (!keyword || keyword.length <= 0) {
        self.searchResultArray = self.totalArray;
    }else{
        NSPredicate *filterPredicate = [NSPredicate predicateWithFormat:@"label contains[c] %@", keyword];
        self.searchResultArray = [self.totalArray filteredArrayUsingPredicate:filterPredicate];
    }
    self.fliterView.dataSource = self.searchResultArray;
    [self.fliterView refresh];
}
#pragma mark - getters
- (UIButton *)comfirmButton {
    if (!_comfirmButton) {
        _comfirmButton = [[UIButton alloc] init];
        [_comfirmButton setTitle:@"确认" forState:UIControlStateNormal];
        [_comfirmButton setTitleColor:HEX_RGB(kTitleWhiteColor) forState:UIControlStateNormal];
        _comfirmButton.titleLabel.font = kCustomFont(@"PingFangSC-Regular", 15.0f);
        [_comfirmButton addTarget:self action:@selector(clickRightItem:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _comfirmButton;
}



- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.searchView.frame), kScreenWidth, kScreenHeight - CGRectGetMaxY(self.searchView.frame)) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[ZYCProtalNoticePushPeopleCell class] forCellReuseIdentifier:NSStringFromClass([ZYCProtalNoticePushPeopleCell class])];
        [_tableView registerClass:[ZYCProtalNoticePushDeptCell class] forCellReuseIdentifier:NSStringFromClass([ZYCProtalNoticePushDeptCell class])];
        if (@available(iOS 15.0, *)) {
            _tableView.sectionHeaderTopPadding = 0;
        }
    }
    return _tableView;
}

- (ZYCFliterMultipleChoiceView *)fliterView {
    if (!_fliterView) {
        _fliterView = [[ZYCFliterMultipleChoiceView alloc] initWithFrame:self.tableView.frame];
        _fliterView.hidden = YES;
        _fliterView.delegate =self;
        [self.view addSubview:_fliterView];
    }
    return _fliterView;
}

- (ZYCSearchBarView *)searchView {
    if (!_searchView) {
        _searchView = [[ZYCSearchBarView alloc] initWithFrame:CGRectMake(0, kNavBarAndStatusBarHeight, kScreenWidth, 63.0f)];
        _searchView.delegate = self;

    }
    return _searchView;
}




- (NSArray *)searchResultArray {
    if (!_searchResultArray) {
        _searchResultArray = [[NSArray alloc] init];
    }
    return _searchResultArray;
}

- (NSMutableArray *)selectArray {
    if (!_selectArray) {
        _selectArray = [NSMutableArray arrayWithCapacity:0];
    }
    return _selectArray;
}


#pragma mark - Action
- (void)clickLeftItem:(UIButton *)sender{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)clickRightItem:(UIButton *)sender{
    // 计算教师.家长总选择的
    NSMutableArray *selectTotalArr = [NSMutableArray arrayWithCapacity:0];
    for (ZYCRoleTreeModel *model in self.dataSource) {
        [selectTotalArr addObjectsFromArray:model.selectArr];// 先算所有的
    }

    for (ZYCRoleTreeModel *model in selectTotalArr) {
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setObject:model.r_id forKey:@"userId"];
        [dict setObject:model.label forKey:@"userName"];
        [self.selectArray addObject:dict];
    }
    if (self.selectBlock) {
        self.selectBlock(self.selectArray);
    }
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark - private method
//递归思想
- (NSArray *)filterSource:(NSArray *)sourceArray type:(NSString *)type{
   if (sourceArray.count == 0)  return nil;
   NSMutableArray *mArr = [NSMutableArray arrayWithCapacity:0];
   for (ZYCRoleTreeModel *model in sourceArray) {
       if ([model.dateType isEqualToString:type]) {
           [mArr addObject:model];
       }
       NSArray *temp = [self filterSource:model.children type:type];
       if (temp.count > 0) {
           [mArr addObjectsFromArray:temp];
       }
   }
   return mArr.copy;
}


- (void)fatherSelectArr:(ZYCRoleTreeModel *)father {
    if (!father) {
        return;
    }
    BOOL isSelected = YES;
    NSMutableArray *selectArr = [NSMutableArray arrayWithCapacity:0];
    for (ZYCRoleTreeModel *child in father.children) {
        if ([child.dateType integerValue] == 4) {
            if (child.isSelected) {
                [selectArr addObject:child];
            }
            else {
                isSelected = NO;
            }
        }
        else {
            [selectArr addObjectsFromArray:child.selectArr];
            if (child.isSelected == NO) {
                isSelected = NO;
            }
        }
    }
    father.isSelected = isSelected;
    father.selectArr = selectArr.copy;
    //递归
    [self fatherSelectArr:father.father];

}

- (NSArray *)childrenArr:(NSArray<ZYCRoleTreeModel *> *)children select:(BOOL)select {
    if (!children)  return nil;
    NSMutableArray *totalArray = [NSMutableArray arrayWithCapacity:0];
    for (ZYCRoleTreeModel *model in children) {
        NSMutableArray *sonArray = [NSMutableArray arrayWithCapacity:0];
        model.isSelected = select;
        [sonArray addObjectsFromArray:[self childrenArr:model.children select:select]];
        model.selectArr = sonArray.copy;
        if (select && [model.dateType integerValue] == 4) {
            [totalArray addObject:model];
        }
        [totalArray addObjectsFromArray:sonArray];
    }
    return totalArray.copy;
}


//- (void)fatherSelect:(ZYCRoleTreeModel *)father {
//    if (!father) {
//        return;
//    }
//    BOOL isSelected = YES;
//    NSInteger cnt = 0;
//    for (ZYCRoleTreeModel *child in father.children) {
//        if ([child.dateType integerValue] == 4) {
//            if (child.isSelected) {
//                cnt++;
//            }
//            else {
//                isSelected = NO;
//            }
//        }
//        else {
//            cnt += child.selectedCnt;
//            if (child.isSelected == NO) {
//                isSelected = NO;
//            }
//        }
//    }
//    father.isSelected = isSelected;
//    father.selectedCnt = cnt;
//    //递归
//    [self fatherSelect:father.father];
//
//}

// 递归
//- (NSInteger)children:(NSArray<ZYCRoleTreeModel *> *)children select:(BOOL)select {
//    if (!children)  return 0;
//    NSInteger total = 0;
//    for (ZYCRoleTreeModel *model in children) {
//        NSInteger son = 0;
//        model.isSelected = select;
//        son += [self children:model.children select:select];
//        model.selectedCnt = son;
//        if (select && [model.dateType integerValue] == 4) {
//            total++;
//        }
//        total += son;
//    }
//    return total;
//}




/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
